import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import uic
from flir_camera_test import FlirCam
import numpy as np
from PyQt5.QtCore import QElapsedTimer
import time
from PyQt5.QtCore import QElapsedTimer
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.bcamera = None
        self.elapsedTime = QElapsedTimer()

        uic.loadUi('graphicsshow.ui', self)
        self.scene = QGraphicsScene(self)
        self.cam = FlirCam()
        self.setupCamList()
        self.combo_Cam.activated.connect(self.initCam)
        self.pushButton_exit.clicked.connect(self.close)
        self.lineEdit_exposure.returnPressed.connect(self.setExposure)
        self.Slider_exposure.valueChanged.connect(self.changeExposureText)
        self.pushButton_reserved.pressed.connect(self.beginAcquisition)
        self.lineEdit_gain.returnPressed.connect(self.setGain)
        self.Slider_gain.valueChanged.connect(self.changGainText)
        self.pushButton_auto_exposure.toggled.connect(self.autoExposure)
        self.pushButton_auto_gain.toggled.connect(self.autoGain)
        self.cam.imageArrived.connect(self.onReceiveImage)
        self.elapsedTime.start()


    @pyqtSlot(np.ndarray, int)

    def onReceiveImage(self, image, count):
        # print(count)
        qimage = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888)
        pix = QPixmap.fromImage(
            qimage.scaled(
                self.ImageBox.size(),
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation
            )
        )
        item = QGraphicsPixmapItem(pix)
        self.scene.addItem(item)
        self.ImageBox.setScene(self.scene)

        elapsed = self.elapsedTime.elapsed()
        count += 1
        print(count / (elapsed * 0.001))

    def beginAcquisition(self):
        self.cam.linshicamBeginAcquisition()


    def autoGain(self):
        if self.pushButton_auto_gain.isChecked():
            print('进入到自动增益设置')
            self.pushButton_auto_gain.setText('关闭自动增益')
            self.lineEdit_gain.setFocusPolicy(Qt.NoFocus)
            self.Slider_gain.setDisabled(True)
            self.setAutoGain(True)
        else:
            self.pushButton_auto_gain.setText('开启自动增益')
            self.lineEdit_gain.setFocusPolicy(Qt.StrongFocus)
            self.Slider_gain.setDisabled(False)
            self.setAutoGain(False)

    def setAutoGain(self, bstate):
        self.cam.autoGain(bstate)

    def test(self):
        print('*')


    def autoExposure(self):
        print('按钮被点击了吗')
        #启动了自动曝光
        if self.pushButton_auto_exposure.isChecked():
            print('开启自动曝光1')
            self.pushButton_auto_exposure.setText('关闭自动曝光')
            self.lineEdit_exposure.setDisabled(True)
            self.Slider_exposure.setDisabled(True)
            self.setAutoExposure(True)

        #关闭了自动曝光
        else:
            self.pushButton_auto_exposure.setText('启动自动曝光')
            self.lineEdit_exposure.setDisabled(False)
            self.Slider_exposure.setDisabled(False)
            self.setAutoExposure(False)


    def setAutoExposure(self,state):
        self.cam.autoExposure(state)


    def setupCamList(self):
        self.combo_Cam.clear()
        CamList = self.cam.returnCamList()
        for cam in CamList:
            self.combo_Cam.addItem(cam)

    def getCurrentCam(self):
        return {0:str(self.combo_Cam.currentText())}

    def initCam(self):
        if self.bcamera:
            self.cam.close()
        self.cam.openCommunications(self.getCurrentCam())

        self.initExposureTime()
        self.initGain()

    def initExposureTime(self):
        minValue = round(self.cam.getMinExposure(),3)
        maxValue = round(self.cam.getMaxExposure(),3)
        print(minValue,maxValue)
        self.Slider_exposure.setRange(minValue,maxValue)

    def setExposure(self):
        self.Slider_exposure.setValue(float(self.lineEdit_exposure.text())*1000)

    def changeExposureText(self, value):
        # np.round(a,b),返回a后面小数点b，四舍五入的值
        print(value)
        self.lineEdit_exposure.setText(str(np.round(self.Slider_exposure.value() * 10 ** (-3), 3)))
        try:
            self.cam.setExposure(value)
            print('设置硬件的曝光时间完毕')
        except Exception as e:
            print('改变设备的曝光时间错误：%s' %e)

    def initGain(self):
        minValue = round(self.cam.getMinGain(), 3)
        maxValue = round(self.cam.getMaxGain(), 3)
        print(minValue, maxValue)
        self.Slider_gain.setRange(minValue, maxValue)

    def setGain(self):
        # print(type(self.lineEdit_gain.text()))
        self.Slider_gain.setValue(int(self.lineEdit_gain.text()))


    def changGainText(self, value):
        # print(value)
        self.lineEdit_gain.setText(str(self.Slider_gain.value()))
        try:
            self.cam.setGain(value)
            print('设置硬件的增益完毕')
        except Exception as e:
            print('改变设备的增益错误：%s' %e)


    def closeEvent(self,event):
        try:
            self.cam.linshicamBeginAcquisition()
            self.cam.close()
        except Exception as e:
            print('Error %s' %e)

        super().closeEvent(event)



if __name__ == '__main__':
    app = QApplication(sys.argv)
    # #print(QStyleFactory.keys())
    app.setStyle('Fusion')
    wnd = MainWindow()
    wnd.setGeometry(
        QStyle.alignedRect(
            Qt.LeftToRight,
            Qt.AlignCenter,
            wnd.size(),
            app.desktop().availableGeometry()
        )
    )
    print('结尾')
    wnd.show()
    sys.exit(app.exec_())